package com.softserveinc.autorent.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

import com.softserveinc.autorent.model.CarPhoto;

@ManagedBean(name = "listing")
@RequestScoped
public class CarPhotoMB implements Serializable {
	private static final long serialVersionUID = 4402067628948579946L;
	@PersistenceContext(unitName = "jpa")
	private EntityManager em;
	private UserTransaction utx;
	int id;
	String description;
	Integer uniqueId;
	private List<?> pictureList = new ArrayList<CarPhoto>();
	
	public CarPhotoMB() {
		//
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public List<?> getPictureList() {
		if (pictureList.size() ==0 )
		{
			Query query = em.createNamedQuery("CarPhoto.findAll");
			pictureList = query.getResultList();
		}	
			
		return pictureList;
	}

	public void setPictureList(List<?> pictureList) {
		this.pictureList = pictureList;
	}

	public CarPhotoMB(int id, String description) {
		this.id = id;
		this.description = description;
	}
	
	
	//Action
	public String upload(Integer id){
		uniqueId = id;
		return "upload/uploadImage";
	}
		
	
	public String create() throws Exception {
		CarPhoto cp = new CarPhoto();
		utx.begin();
		em.merge(cp);
		em.persist(cp);
		utx.commit();
		pictureList = new ArrayList<CarPhoto>();
		return null;

	}
	
	public String prepareUniqueIdentifier() {
        return UUID.randomUUID().toString()+"png";
    }   
		
	public String saveToDatabase() throws Exception {
		ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
		String realPath = ctx.getRealPath("upload/" + uniqueId + "_image.jpg");
		File file = new File(realPath);
		
		FileInputStream infile = new FileInputStream(file);
		byte[] buffer = new byte[(int) file.length()];
		infile.close();
		
		CarPhoto photo = new CarPhoto(uniqueId, description, buffer);
		utx.begin();
		em.merge(photo);
		utx.commit();
		photo = null;
		file.delete();
		
		return "createimage";
	}
	
	
	
	

}
